﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Threading;
using System.Windows.Threading;
using SpaceNeedle.x6473.WindowsPhone.ViewModels;
using SpaceNeedle.x6473.WindowsPhone.Common;
using Windows.Networking.Connectivity;
using SpaceNeedle.SDK.WindowsPhone.Views;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;

namespace SpaceNeedle.x6473.WindowsPhone.Views
{
    public class UploadsView : ViewBase<UploadsViewModel> { }
    public partial class Uploads : UploadsView
    {
        private bool cameFromRequest;
        
        public Uploads()
        {
            InitializeComponent();
            this.Loaded += Uploads_Loaded;

            this.BackKeyPress += Uploads_BackKeyPress;
        }

        void Uploads_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if(cameFromRequest)
            {
                this.NavigationService.RemoveBackEntry();
            }
        }

        private void UpdateRequestsList()
        {
            if (this.ViewModel.TransferRequests != null)
            {
                foreach (var request in this.ViewModel.TransferRequests)
                {
                    request.Dispose();
                }
            }

            this.ViewModel.TransferRequests = BackgroundTransferService.Requests;
        }

        private void UpdateUI()
        {
            UpdateRequestsList();
        }

        void Uploads_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string param;

            if (NavigationContext.QueryString.TryGetValue("fromRequest", out param))
            {
                this.cameFromRequest = Convert.ToBoolean(param);
            }

            InitialTransferStatusCheck();
            UpdateUI();
        }

        private void InitialTransferStatusCheck()
        {
            UpdateRequestsList();

            foreach (var transfer in this.ViewModel.TransferRequests)
            {
                transfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                transfer.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);

                ProcessTransfer(transfer);
            }
        }

        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:

                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        RemoveTransferRequest(transfer.RequestId);
                    
                        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            string filename = transfer.Tag;
                        
                            if (isoStore.FileExists(filename))
                            {
                                isoStore.DeleteFile(filename);
                            }

                            isoStore.MoveFile(transfer.UploadLocation.OriginalString, filename);
                        }
                    }
                    else
                    {
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {

                        }
                    }
                    break;
            }
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            UpdateUI();
        }

        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            UpdateUI();
        }

        
        private void RemoveTransferRequest(string transferID)
        {
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception e)
            {

            }
        }

        private void OnCancelAllAppBarButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Tem certeza que deseja cancelar todos os Uploads?", "Uploads", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                foreach (var transfer in BackgroundTransferService.Requests)
                {
                    RemoveTransferRequest(transfer.RequestId);
                }

                UpdateUI();
            }
        }

        private void OnAboutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.AboutCommand.Execute(null);
        }

        private void OnSignOutMenuItem_Click(object sender, EventArgs e)
        {
            this.ViewModel.SignOutCommand.Execute(null);
        }

        private void TransferRequest_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (MessageBox.Show("Deseja cancelar o Upload?", "Uploads", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                string transferID = ((Grid)sender).Tag as string;

                RemoveTransferRequest(transferID);

                UpdateUI();
            }
        }
    }
}